package com.pocketsweet.ui;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.pocketsweet.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.pocketsweet.ui.touch.TouchActivity;

public class ImageViewFlipper extends TouchActivity {

	private static final int EXIT = 0;
	private static final int SWIPE_MIN_DISTANCE = 120;
	private static final int SWIPE_MAX_OFF_PATH = 250;
	private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	private GestureDetector gestureDetector;
	View.OnTouchListener gestureListener;
	private Animation slideLeftIn;
	private Animation slideLeftOut;
	private Animation slideRightIn;
	private Animation slideRightOut;
	private ViewFlipper viewFlipper;
	private int currentView = 0;
	private ArrayList<String> ImageList = new ArrayList<String>();
	private int currentIndex = 0;
	private int maxIndex = 0;
	private ImageView currentImageView = null;

	private float mMinZoomScale = 1;

	FileOutputStream output = null;
	OutputStreamWriter writer = null;
	private TextView tvNum;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.view_image_scan);
		ImageView iv = (ImageView) findViewById(R.id.zero);
		tvNum = (TextView) findViewById(R.id.tvNum);
		/*
		 * iv.setOnTouchListener(this);
		 * findViewById(R.id.one).setOnTouchListener(this);
		 * findViewById(R.id.two).setOnTouchListener(this);
		 */

		// 初始化ImageList
		Intent intent = getIntent();
		ImageList = intent.getStringArrayListExtra("ImageList");
		currentIndex = intent.getIntExtra("index", 0);
		tvNum.setText(currentIndex + 1 + "/" + ImageList.size());
		maxIndex = ImageList.size() - 1;

		viewFlipper = (ViewFlipper) findViewById(R.id.flipper);

		slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
		slideLeftOut = AnimationUtils
				.loadAnimation(this, R.anim.slide_left_out);
		slideRightIn = AnimationUtils
				.loadAnimation(this, R.anim.slide_right_in);
		slideRightOut = AnimationUtils.loadAnimation(this,
				R.anim.slide_right_out);

		viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_in));
		viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_out));
		// UserService.displayBigImage(ImageList.get(currentIndex), iv);
		Bitmap bitmap = ImageLoader.getInstance().loadImageSync(
				ImageList.get(currentIndex));
		BitmapDrawable bd = new BitmapDrawable(bitmap);
		iv.setImageDrawable(bd);
		resetImage(iv,bd);
		System.gc();

		gestureDetector = new GestureDetector(new MyGestureDetector());
		gestureListener = new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (gestureDetector.onTouchEvent(event)) {
					return true;
				}
				return false;
			}
		};
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		int NONE = Menu.NONE;
		menu.add(NONE, EXIT, NONE, "Exit");
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case EXIT:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	protected void onPause() {
		super.onPause();
	}

	protected void onResume() {
		super.onResume();
	}

	class MyGestureDetector extends SimpleOnGestureListener {
		private int toggleCount = 0;

		@Override
		public boolean onDoubleTap(final MotionEvent e) {

			ImageView view = (ImageView) findViewById(R.id.zero);
			switch (currentView) {
			case 0:
				view = (ImageView) findViewById(R.id.zero);
				break;
			case 1:
				view = (ImageView) findViewById(R.id.one);
				break;
			case 2:
				view = (ImageView) findViewById(R.id.two);
				break;
			}

			resetImage(view, view.getDrawable());
			return true;
		}

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			try {
				if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
					return false;
				// right to left swipe
				if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					viewFlipper.setInAnimation(slideLeftIn);
					viewFlipper.setOutAnimation(slideLeftOut);

					if (currentIndex == maxIndex) {
						currentIndex = 0;
					} else {
						currentIndex = currentIndex + 1;
					}
					tvNum.setText(currentIndex + 1 + "/" + ImageList.size());
					ImageView iv;
					Bitmap bitmap = ImageLoader.getInstance().loadImageSync(
							ImageList.get(currentIndex));
					BitmapDrawable bd = new BitmapDrawable(bitmap);
					if (currentView == 0) {
						currentView = 1;
						iv = (ImageView) findViewById(R.id.one);						
						iv.setImageDrawable(bd);
						System.gc();
					} else if (currentView == 1) {
						currentView = 2;
						iv = (ImageView) findViewById(R.id.two);
						iv.setImageDrawable(bd);
						System.gc();
					} else {
						currentView = 0;
						iv = (ImageView) findViewById(R.id.zero);
						iv.setImageDrawable(bd);
						System.gc();
					}
					resetImage(iv,bd);
//					Log.v("ImageViewFlipper", "Current View: " + currentView);
					viewFlipper.showNext();

					return true;
				} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					viewFlipper.setInAnimation(slideRightIn);
					viewFlipper.setOutAnimation(slideRightOut);

					if (currentIndex == 0) {
						currentIndex = maxIndex;
					} else {
						currentIndex = currentIndex - 1;
					}
					tvNum.setText(currentIndex + 1 + "/" + ImageList.size());
					ImageView iv;
					Bitmap bitmap = ImageLoader.getInstance().loadImageSync(
							ImageList.get(currentIndex));
					BitmapDrawable bd = new BitmapDrawable(bitmap);
					if (currentView == 0) {
						currentView = 2;
						iv = (ImageView) findViewById(R.id.two);
						iv.setImageDrawable(bd);
						System.gc();
					} else if (currentView == 2) {
						currentView = 1;
						iv = (ImageView) findViewById(R.id.one);
						iv.setImageDrawable(bd);
						System.gc();
					} else {
						currentView = 0;
						iv = (ImageView) findViewById(R.id.zero);
						iv.setImageDrawable(bd);
						System.gc();
					}
					resetImage(iv,bd);
//					Log.v("ImageViewFlipper", "Current View: " + currentView);
					viewFlipper.showPrevious();
					return true;
				}
			} catch (Exception e) {
				// nothing
			}
			return false;
		}

	}

	@Override
	public void resetImage(ImageView iv, Drawable draw) {
		Display display = ((WindowManager) getSystemService(WINDOW_SERVICE))
				.getDefaultDisplay();
		int rotation = display.getRotation();

		int orientation = 0;
		if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180)
			orientation = 0;
		else
			orientation = 1;

		matrix = new Matrix();
		matrix.setTranslate(1f, 1f);
		float scale = 1;

		mMinZoomScale = 1;
		if (orientation == 0
		// && (float)draw.getIntrinsicWidth() >
		// (float)getWindowManager().getDefaultDisplay().getWidth()
		) {

			scale = (float) getWindowManager().getDefaultDisplay().getWidth()
					/ (float) draw.getIntrinsicWidth();
			mMinZoomScale = scale;
			matrix.postScale(scale, scale);

			iv.setImageMatrix(matrix);
		} else if (orientation == 1
		// && (float)draw.getIntrinsicHeight() >
		// (float)getWindowManager().getDefaultDisplay().getHeight()
		) {
			scale = (float) getWindowManager().getDefaultDisplay().getHeight()
					/ (float) draw.getIntrinsicHeight();
			mMinZoomScale = scale;
			matrix.postScale(scale, scale);

			iv.setImageMatrix(matrix);
		}

		float transX = (float) getWindowManager().getDefaultDisplay()
				.getWidth()
				/ 2
				- (float) (draw.getIntrinsicWidth() * scale)
				/ 2;

		float transY = (float) getWindowManager().getDefaultDisplay()
				.getHeight()
				/ 2
				- (float) (draw.getIntrinsicHeight() * scale)
				/ 2

		;
		matrix.postTranslate(transX, transY);
		iv.setImageMatrix(matrix);
	}

	@Override
	public float getMinZoomScale() {
		return mMinZoomScale;
	}

	@Override
	public boolean onTouchEvent(MotionEvent rawEvent) {
		if (gestureDetector.onTouchEvent(rawEvent))
			return true;

		ImageView view = (ImageView) findViewById(R.id.zero);
		switch (currentView) {
		case 0:
			view = (ImageView) findViewById(R.id.zero);
			break;
		case 1:
			view = (ImageView) findViewById(R.id.one);
			break;
		case 2:
			view = (ImageView) findViewById(R.id.two);
			break;
		}
		onTouchEvented(view, rawEvent);

		return true;
	}

	public static Drawable getDrawable(String urlpath) {
		Drawable d = null;
		try {
			URL url = new URL(urlpath);
			URLConnection conn = url.openConnection();
			conn.connect();
			InputStream in;
			in = conn.getInputStream();
			d = Drawable.createFromStream(in, urlpath);
			// TODO Auto-generated catch block
		} catch (IOException e) {
			e.printStackTrace();
		}
		return d;
	}

	public void back(View v) {
		this.finish();
	}
}